package com.rockcent.mall.controller;

import com.aliyun.oss.OSSClient;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.BigDecimalUtils;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.Prop;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.LocationHelper;
import com.rockcent.mall.lib.helper.QRCodeHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MerchantChannelStatisticsService;
import com.rockcent.service.MerchantProductSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by zhangjh on 2016/9/27.
 */
@RestController
public class MerchantController extends BaseController {


    private final Logger log = LoggerFactory.getLogger(MerchantController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private QRCodeHelper qrCodeHelper;

    @Autowired
    private MerchantProductSrv merchantProductSrvImpl;


    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private MerchantCertifyRepository merchantCertifyRepository;

    @Autowired
    private MerchantOrderRepository merchantOrderRepository;

    @Autowired
    private MallRepository mallRepository;


    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private OSSClient ossClient;
    @Autowired
    private UploadImageFileRepository uploadImageFileRepository;

    @Autowired
    private MarketMerchantCooperationRepository marketMerchantCooperationRepository;

    @Autowired
    private MerchantCouponRepository merchantCouponRepository;

    @Autowired
    private MerchantProductRepository merchantProductRepository;

    @Autowired
    private MerchantOrderVerificationRepository merchantOrderVerificationRepository;

    @Autowired
    private MerchantGiftPacketRepository merchantGiftPacketRepository;

    @Autowired
    private MerchantChannelRepository merchantChannelRepository;

    @Autowired
    private LocationHelper locationHelper;

    @Autowired
    private Prop prop;

    @Autowired
    private MerchantBankRepository merchantBankRepository;

    @Autowired
    private MerchantChannelStatisticsService merchantChannelStatisticsService;

    /**
     * @api {put} /merchant/update 更新商户信息
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} name       商城名字
     * @apiParam {String} intro      商城简介
     * @apiParam {String} logoUrl      商城图标Url
     * @apiParam {String} faceUrl      商城封面Url
     * @apiParam {String} customerServiceContact 商城客服电话
     * @apiParam {Boolean=true,false} prodAudit 是否产品审核
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_UPDATE, method = RequestMethod.PUT)
    public JsonResult update(@RequestBody MerchantDto vo, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Merchant merchant = merchantRepository.findOne(userInfoDto.merchant.getId());
            if (StringUtils.isNotBlank(vo.getName())) {
                merchant.setName(vo.getName());
                //修改对应产品的merchantName

            }

            if (StringUtils.isNotBlank(vo.getCustomerServiceContact())) {
                merchant.setCustomerServiceContact(vo.getCustomerServiceContact());
            }
            if (StringUtils.isNotBlank(vo.getIntro())) {
                merchant.setIntro(vo.getIntro());
            }
            if (StringUtils.isNotBlank(vo.getFaceUrl())) {
                merchant.setFaceUrl(vo.getFaceUrl());
            }
            if (StringUtils.isNotBlank(vo.getLogoUrl())) {
                merchant.setLogoUrl(vo.getLogoUrl());
            }

            if (vo.getProdAudit() != null) {
                merchant.setProdAudit(vo.getProdAudit());
            }
            merchantRepository.save(merchant);
            merchantProductSrvImpl.updateMerchantProductInfo(merchant);

        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /merchant/info 商户 信息
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     *      "id": 1,
     *      "name": "请我诶如",
     *      "email": "renzijian2@rockcent.com",
     *      "intro": "快快快快快快快",
     *      "status": "VERIFIED",
     *      "mallId": 1,
     *      "customerServiceContact": "13826988512",
     *      "prodAudit": true,
     *      "faceUrl": "/dev/merchant/face/20169/2915259910c33bcb0f-af74-4296-a35f-acac2ff78056burnout paradise - 1 - esrb e pegi 7+.jps",
     *      "logoUrl": "/dev/merchant/logo/20169/29162558336f7a66139-31e8-4d12-a23b-b5b65cc3a09aguitar hero 3 - 2 - esrb t pegi 12+.jps",
     *      "merchantRegisterType": "MOBILE",
     *      "type": "PERSONAL",
     *      "dateEnabled":"试用开始时间",
     *      "dateDisabled":"试用结束时间",
     *      "probationaryPeriodDays":"累计试用天数",
     *      "settlementDate":"结算日",
     *      "gracePeriodEndDate":"缓冲期截止日期",
     *      "expiredDays":"剩余使用天数"
     *      }
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_INFO, method = RequestMethod.GET)
    public JsonResult info(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            Merchant merchant = merchantRepository.findOne(userInfoDto.merchant.getId());
            if (merchant == null) {
                jsonResult.remind("加载信息出错",log);
                return;
            }
            jsonResult.data = merchant;

        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/certify/info 商户认证信息
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code" "1",
     * "desc" "成功",
     * "data" {
     *      "id" 2,
     *      "dateCreated" "2016-06-14 20:12:31",
     *      "lastUpdated" "2016-06-14 20:12:57",
     *      "version" 1,
     *      "auditRemark" "通过",
     *      "companyName" "rockcent",
     *      "contactAddress" "kecun",
     *      "contactPhone" "13826988206",
     *      "dateAudited" "2016-06-14 20:12:57",
     *      "idcardCode" "440683198806215134",
     *      "licenseCode" "4444444",
     *      "locationId" 1,
     *      "realName"  "御风林海111",
     *      "type"  "PERSONAL",
     *      "email"  "761011857@qq.com",
     *      "idCardPicUrl" http://uploads.rockcent.com/dev/merchant/logo/201610/10144718260a1c37685-0d2e-4d60-b531-82f8cfd30a46Tulips.jpg
     *      "merchantId" 1
     *      }
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_CERTIFY_INFO, method = RequestMethod.GET)
    public JsonResult certifyInfo(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            MerchantCertify merchantCertify = merchantCertifyRepository.findByMerchantIdAndMallId(userInfoDto.merchant.getId(), userInfoDto.mall.getId());
            if (merchantCertify == null) {
                jsonResult.remind("加载数据出错,请检查数据完整性", log);
                return;
            }
            if (merchantCertify.getLocationId() != null) {
                LocationDto locationDto = locationHelper.getFullLocation(merchantCertify.getLocationId());
                merchantCertify.setLocationStr(locationDto.getProviceName() + locationDto.getCityName() + locationDto.getLocationName() + merchantCertify.getContactAddress());
            }
            jsonResult.data = merchantCertify;

        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /merchant/certify/save 提交/修改商户认证信息
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken     用户token
     * @apiHeader {String} domain        请求域名
     * @apiParam {String} type <code>必要参数 可选值 PERSONAL | COMPANY</code> 注册类型
     * @apiParam {String} contactAddress 联系地址
     * @apiParam {String} contactPhone   联系电话
     * @apiParam {String} idcardCode     联系人身份证号码
     * @apiParam {String} idCardPicUrl   联系人身份证正面扫描件路径
     * @apiParam {String} email          电子邮件
     * @apiParam {String} companyName <code>注册类型为企业时，必传</code> 企业名字
     * @apiParam {String} licenseCode <code>注册类型为企业时，必传</code> 企业营业执照号
     * @apiParam {String} licensePicUrl <code>注册类型为企业时，必传</code> 营业执照扫描件URL
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code" "1",
     * "desc" "成功",
     * "data" {
     *      "id" 2,
     *      "dateCreated" "2016-06-14 20:12:31",
     *      "lastUpdated" "2016-06-14 20:12:57",
     *      "version" 1,
     *      "auditRemark" "通过",
     *      "companyName" "rockcent",
     *      "contactAddress" "kecun",
     *      "contactPhone" "13826988206",
     *      "dateAudited" "2016-06-14 20:12:57",
     *      "idcardCode" "440683198806215134",
     *      "licenseCode" "4444444",
     *      "locationId" 1,
     *      "realName"  "御风林海111",
     *      "type"  "PERSONAL",
     *      "email"  "761011857@qq.com",
     *      "merchantId" 1
     *      }
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_CERTIFY_SAVE, method = RequestMethod.POST)
    public JsonResult saveCertifyInfo(@RequestBody MerchantCertifyDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (!EnumUtils.isValidEnum(CertifyType.class, dto.getType())) {
                jsonResult.remind("认证类型 只允许PERSONAL(个人认证), COMPANY(企业认证)",log);
                return;
            }
            Merchant merchant = this.merchantRepository.getOne(userInfoDto.merchant.getId());
            MerchantCertify merchantCertify = merchantCertifyRepository.getCertifyByMerchantId(userInfoDto.merchant.getId());
            if (merchantCertify == null) {
                merchantCertify = new MerchantCertify();
            }
            merchantCertify.setMerchantId(merchant.getId());
            merchantCertify.setLastUpdated(new java.util.Date());
            merchantCertify.setIsDelete(Whether.NO);
            merchantCertify.setContactAddress(dto.getContactAddress());
            merchantCertify.setContactPhone(dto.getContactPhone());
            merchantCertify.setEmail(dto.getEmail());
            merchantCertify.setIdcardCode(dto.getIdcardCode());
            merchantCertify.setMallId(merchant.getMallId());
            merchantCertify.setType(CertifyType.valueOf(dto.getType()));
            merchantCertify.setUserInfoId(userInfoDto.getId());
            if (CertifyType.COMPANY==merchantCertify.getType()) {
                merchantCertify.setCompanyName(dto.getCompanyName());
                merchantCertify.setLicenseCode(dto.getLicenseCode());
                merchantCertify.setLicensePicUrl(dto.getLicensePicUrl());
            }
            merchantCertify.setLocationId(dto.getLocationId());
            merchantCertify.setIdCardPicUrl(dto.getIdCardPicUrl());
            merchantCertify.setRealName(dto.getRealName());

            merchant.setStatus(MerchantStatus.VERIFING);
            merchantCertify.setAuditRemark("审核中");
            this.merchantRepository.saveAndFlush(merchant);
            this.merchantCertifyRepository.saveAndFlush(merchantCertify);
            jsonResult.data = merchantCertify;

            //广播消息l
            SysMessageHelper.SINGLETON.pushOpMsg(SysMessageConstants.M2M_MALL_MERCHANT_CERTIFY_SAVE_PENDING_AUDIT, null, merchant.getMallId(),null);

        };
        return doing.go(request, log);
    }


    /**
     * @api{post} /merchant/face/upload 商城封面图片上传
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiParam file   封面文件
     * @apiParam {String}  businessType <code>必要参数 商城封面：MERCHANT_FACE；商城Logo：MERCHANT_LOGO</code> 业务类型
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data":
     *  {
     *      "id": 43,
     *      "path": "http://uploads.rockcent.com//dev/merchant/face/20169/29143864901916f359-04ab-4526-8f1d-e4d74293031dburnout paradise - 1 - esrb e pegi 7+.jps"
     *  }
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_FACE_UPLOAD, method = RequestMethod.POST)
    public JsonResult uploadFaceFile(MultipartFile file, String businessType, HttpServletRequest request) {
        RestDoing restDoing = jsonResult -> {
            UserInfoDto userInfoDto = userHelper.getSession(request);
            if (file == null) {
                jsonResult.errorParam("file 不能为空",log);
                return;
            }
            if (businessType == null) {
                jsonResult.errorParam("businessType 不能为空",log);
                return;
            }

            if (!EnumUtils.isValidEnum(UploadFileBusinessType.class, businessType)) {
                jsonResult.remind("业务类型 只允许 MERCHANT_FACE(\"/merchant/face\",\"商城封面图\")和 MERCHANT_LOGO(\"/merchant/logo\",\"商城图标\")",log);
                return;
            }
            UploadImageFile uploadImageFile = new UploadImageFile();
            // 文件名
            String fileName = uploadImageFile.genFileName(file.getOriginalFilename());
            String allPath = uploadImageFile.genAllPath(prop.env, UploadFileBusinessType.valueOf(businessType), fileName);

            uploadImageFile.setSize(file.getSize());
            uploadImageFile.setOriginFileName(file.getOriginalFilename());
            uploadImageFile.setFileName(fileName.toString());
            uploadImageFile.setPath("/" + allPath);
            uploadImageFile.setBusinessType(UploadFileBusinessType.valueOf(businessType));
            uploadImageFile.setUserInfoId(userInfoDto.getId());
            if(null!=userInfoDto.merchant){
                uploadImageFile.setMerchantId(userInfoDto.merchant.getId());
            }
//            uploadImageFile.setMerchantId(userInfoDto.merchant.getId());
            uploadImageFile.setMallId(userInfoDto.mall.getId());
            uploadImageFile = uploadImageFileRepository.save(uploadImageFile);
            ossClient.putObject(prop.aliyunOssBucketName, allPath, file.getInputStream());
            UploadImageFileDto uploadImageFileDto = new UploadImageFileDto();
            uploadImageFileDto.setPath(prop.domainUploadsHttp + "/" + uploadImageFile.getPath());
            uploadImageFileDto.setId(uploadImageFile.getId());
            jsonResult.data = uploadImageFileDto;
        };
        return restDoing.go(request, log);
    }

    /**
     *
     /**
     * @api{get} /merchant/index 商户概况
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     *
     * @apiSuccess {Long} waitPayCount 待付款订单数
     * @apiSuccess {Long} waitShippedCount 待发货数量
     * @apiSuccess {Long} waitShopPickCount 待自提数量
     * @apiSuccess {Long} waitIsuseCount 待评价数量
     *
     * @apiSuccess {Long} waitVerify 待审核分销商数量
     *
     * @apiSuccess {Long} productWaitVerify 待审核数量
     * @apiSuccess {Long} productverifyFail 审核不通过数量
     * @apiSuccess {Long} productIllegal 违规数量
     *
     * @apiSuccess {Long} viewCustomerCount 访客数
     * @apiSuccess {Long} viewChannelCustomerCount 渠道访客数
     *
     * @apiSuccess {Long} orderCount 下单数
     * @apiSuccess {Long} orderCustomerCount 下单人数
     * @apiSuccess {Long} orderProductCount 下单产品数
     * @apiSuccess {Long} orderTotal 下单金额
     *
     * @apiSuccess {Long} payedOrderCount 支付订单数
     * @apiSuccess {Long} payedOrderCustomerCount 支付人数
     * @apiSuccess {Long} payedProductCount 支付产品数
     * @apiSuccess {Long} payOrderTotal 支付金额
     *
     * @apiSuccess {Long} verifyOrderCount 核销订单数
     * @apiSuccess {Long} verifyCustomerCount 核销人数
     * @apiSuccess {Long} verifyProductCount 核销产品数
     * @apiSuccess {Long} verifyOrderTotal 核销金额
     *
     * @apiSuccess {Long} orderRate下单转化率
     * @apiSuccess {Long} orderCustomerCount 支付转化率
     * @apiSuccess {Long} verifyRate 核销转化率
     *
     * @apiSuccess {Long} latestProductCount 新上产品数
     * @apiSuccess {Long} newProductViewCount 新上产品访问量
     * @apiSuccess {Long} collectProductCount 收藏产品数待定
     * @apiSuccess {Long} lastBuyProductCount 加购产品数
     *
     * @apiSuccess {List} top3ProductSelling 热销产品列表
     *
     * @apiSuccess {Long} newCustomerCount 新客户数
     * @apiSuccess {Long} newCustomerOrderCount 新客户下单数
     * @apiSuccess {Long} newCustomerOrderTotal 新客户购买金额
     * @apiSuccess {Long} newCustomerOrderAvg 新客户－客单价
     *
     * @apiSuccess {Long} oldCustomerCount 老客户数
     * @apiSuccess {Long} oldCustomerOrderCount 老客户下单数
     * @apiSuccess {Long} oldCustomerOrderTotal 老客户购买金额
     * @apiSuccess {Long} oldCustomerOrderAvg 老客户－客单价
     *
     * @apiSuccess {Long} couponCount 优惠券数量
     * @apiSuccess {Long} redPacketCount 红包数量待定
     * @apiSuccess {Long} giftPacketCount 礼包数量
     *
     * @apiSuccess {List} top5Channels 渠道活跃指数　根据渠道访问量，出售量，下单转化率　从高到低排列
     * @apiSuccess {List} top5Article 帮助中心文章列表
     *
     * @apiSuccessExample {json} Success-Response:
     * {"
     * "code":"1",
     * "desc":"成功","
     * data":
     * {
     *      "verifyOrderCount":0,
     *      "oldCustomerOrderCount":0,
     *      "top5Channels":[],
     *      "productWaitVerify":0,
     *      "couponCount":17,
     *      "waitPayCount":0,
     *      "waitVerify":0,
     *      "viewChannelCustomerCount":0,
     *      "oldCustomerOrderTotal":0.0,
     *      "latestProductCount":0,
     *      "productverifyFail":0,
     *      "waitShopPickCount":0,
     *      "top5Article":[
     *      {
     *       "id":17,
     *       "name":"如何注册"
     *      }
     *      ],
     *      "newProductViewCount":0,
     *      "payedOrderCustomerCount":0,
     *      "payedRate":0.0,
     *      "verifyRate":0.0,
     *      "waitIsuseCount":0,
     *      "newCustomerOrderAvg":"0",
     *      "newCustomerOrderCount":0,
     *      "payOrderTotal":0.0,
     *      "orderCustomerCount":0,
     *      "verifyOrderTotal":0.0,
     *      "newCustomerOrderTotal":0.0,
     *      "verifyProductCount":0,
     *      "productIllegal":0,
     *      "orderCount":0,
     *      "oldCustomerOrderAvg":"0",
     *      "giftPacketCount":0,
     *      "orderRate":0.0,
     *      "waitShippedCount":0,
     *      "oldCustomerCount":0,
     *      "orderProductCount":0,
     *      "orderTotal":0.0,
     *      "lastBuyProductCount":0,
     *      "payedOrderCount":0,
     *      "payedProductCount":0,
     *      "newCustomerCount":0,
     *      "viewCustomerCount":2,
     *      "verifyCustomerCount":0,
     *      "top3ProductSelling":[]
     * }
     * }
     *
     */
    @RequestMapping(value = Routes.MERCHANT_INDEX, method = RequestMethod.GET)
    public JsonResult merchantIndex(MerchantCertifyDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            // MerchantDto merchant = merchantRepository.getMechantInforById(userInfoDto.merchant.getId());
            //待付款订单数
            Long waitPayCount = merchantOrderRepository.getOrderStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), OrderStatus.WAIT_PAYING, null);
            if (waitPayCount == null) {
                waitPayCount = 0l;
            }
            resultMap.put("waitPayCount", waitPayCount);
            // 待发货数量
            Long waitShippedCount = merchantOrderRepository.getOrderStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), OrderStatus.WAIT_SHIPPED, null);
            if (waitShippedCount == null) {
                waitShippedCount = 0l;
            }
            resultMap.put("waitShippedCount", waitShippedCount);
            //待自提数量
            Long waitShopPickCount = merchantOrderRepository.getOrderStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), OrderStatus.WAIT_SHOP_PICKUP, null);
            if (waitShopPickCount == null) {
                waitShopPickCount = 0l;
            }
            resultMap.put("waitShopPickCount", waitShopPickCount);

            //待评价数量
            Long waitIsuseCount = merchantOrderRepository.getOrderStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), null, EvaluateStatus.WAIT_EVALUATE);
            if (waitIsuseCount == null) {
                waitIsuseCount = 0l;
            }
            resultMap.put("waitIsuseCount", waitIsuseCount);
            //待审核分销商数量
            Long waitVerify = marketMerchantCooperationRepository.getMarketMerchantWaitVerify(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            resultMap.put("waitVerify", waitVerify);
            if (waitVerify == null) {
                waitVerify = 0l;
            }
            //产品管理-待审核数量
            Long productWaitVerify = merchantProductRepository.getProductWithVerifyStatus(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), ProductStatus.WAIT_AUDIT);
            System.out.println("productWaitVerify=" + productWaitVerify);
            if (productWaitVerify == null) {
                productWaitVerify = 0l;
            }
            resultMap.put("productWaitVerify", productWaitVerify);
            //产品管理-审核不通过数量
            Long productverifyFail = merchantProductRepository.getProductWithVerifyStatus(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), ProductStatus.AUDIT_FAIL);

            if (productverifyFail == null) {
                productverifyFail = 0l;
            }
            resultMap.put("productverifyFail", productverifyFail);
            //违规数量
            Long productIllegal = merchantProductRepository.getProductWithVerifyStatus(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), ProductStatus.ILLEGAL);

            if (productIllegal == null) {
                productIllegal = 0l;
            }
            resultMap.put("productIllegal", productIllegal);
            //访客数
            Long viewCustomerCount = merchantRepository.getViewCountYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), ProductEventType.VIEWED, null);

            if (viewCustomerCount == null) {
                viewCustomerCount = 0l;
            }
            resultMap.put("viewCustomerCount", viewCustomerCount);
            //渠道访客数
            Long viewChannelCustomerCount = merchantRepository.getViewCountYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), ProductEventType.VIEWED, Whether.YES);
            if (viewChannelCustomerCount == null) {
                viewChannelCustomerCount = 0l;
            }
            resultMap.put("viewChannelCustomerCount", viewChannelCustomerCount);
            //下单数
            Long orderCount = merchantOrderRepository.getOrderNumStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), OrderEventType.ORDERED);
            if (orderCount == null) {
                orderCount = 0l;
            }
            resultMap.put("orderCount", orderCount);
            //下单人数
            Long orderCustomerCount = merchantOrderRepository.getOrderCustomerStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (orderCustomerCount == null) {
                orderCustomerCount = 0l;
            }
            resultMap.put("orderCustomerCount", orderCustomerCount);
            //下单产品数
            Long orderProductCount = merchantOrderRepository.getOrderProductStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (orderProductCount == null) {
                orderProductCount = 0l;
            }
            resultMap.put("orderProductCount", orderProductCount);
            //下单金额
            Double orderTotal = merchantOrderRepository.getOrderTotalSumStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (orderTotal == null) {
                orderTotal = 0d;
            }
            resultMap.put("orderTotal", BigDecimalUtils.setScale(orderTotal));
            //支付订单数
            Long payedOrderCount = merchantOrderRepository.getOrderNumStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), OrderEventType.PAYED);
            if (payedOrderCount == null) {
                payedOrderCount = 0l;
            }
            resultMap.put("payedOrderCount", payedOrderCount);
            //支付人数
            Long payedOrderCustomerCount = merchantOrderRepository.getPayOrderCustomerCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), OrderEventType.PAYED);
            if (payedOrderCustomerCount == null) {
                payedOrderCustomerCount = 0l;
            }
            resultMap.put("payedOrderCustomerCount", payedOrderCustomerCount);
            //支付产品数
            Long payedProductCount = merchantOrderRepository.getPayProductCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), OrderEventType.PAYED);
            if (payedProductCount == null) {
                payedProductCount = 0l;
            }
            resultMap.put("payedProductCount", payedProductCount);
            //支付金额
            Double payOrderTotal = merchantOrderRepository.getPayOrderTotalStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId(), OrderEventType.PAYED);
            if (payOrderTotal == null) {
                payOrderTotal = 0d;
            }
            resultMap.put("payOrderTotal", BigDecimalUtils.setScale(payOrderTotal));
            //核销订单数
            Long verifyOrderCount = merchantOrderVerificationRepository.getVerifyOrderCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (verifyOrderCount == null) {
                verifyOrderCount = 0l;
            }
            resultMap.put("verifyOrderCount", verifyOrderCount);
            //核销人数
            Long verifyCustomerCount = merchantOrderVerificationRepository.getVerifyCustomerCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (verifyCustomerCount == null) {
                verifyCustomerCount = 0l;
            }
            resultMap.put("verifyCustomerCount", verifyCustomerCount);
            //核销产品数
            Long verifyProductCount = merchantOrderVerificationRepository.getVerifyProductCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (verifyProductCount == null) {
                verifyProductCount = 0l;
            }
            resultMap.put("verifyProductCount", verifyProductCount);
            //核销金额
            Double verifyOrderTotal = merchantOrderVerificationRepository.getVerifyOrderTotalStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (verifyOrderTotal == null) {
                verifyOrderTotal = 0d;
            }
            resultMap.put("verifyOrderTotal", BigDecimalUtils.setScale(verifyOrderTotal));
            //下单转化率＝下单人数／访客数
            Double orderRate = 0d;
            if (viewCustomerCount != null && viewCustomerCount != 0) {
                orderRate = Double.valueOf((orderCustomerCount / viewCustomerCount) * 100);
            }
            resultMap.put("orderRate", orderRate);
            //支付转化率=支付人数／下单人数
            Double payedRate = 0d;
            if (orderCustomerCount != null && orderCustomerCount.longValue() != 0) {
                payedRate = Double.valueOf((payedOrderCustomerCount.longValue() / orderCustomerCount.longValue()) * 100);
            }
            resultMap.put("payedRate", BigDecimalUtils.setScale(payedRate));
            //核销转化率=核销人数/支付人数
            Double verifyRate = 0d;
            if (payedOrderCustomerCount!=null && payedOrderCustomerCount.longValue() != 0) {
                verifyRate = Double.valueOf((verifyCustomerCount.longValue() / payedOrderCustomerCount.longValue()) * 100);
            }
            resultMap.put("verifyRate", BigDecimalUtils.setScale(verifyRate));
            //新上产品数
            Long latestProductCount = merchantProductRepository.getLatestProductCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (latestProductCount == null) {
                latestProductCount = 0l;
            }
            resultMap.put("latestProductCount", latestProductCount);
            //新上产品访问量
            Long newProductViewCount = merchantProductRepository.getNewProductViewCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (newProductViewCount == null) {
                newProductViewCount = 0l;
            }
            resultMap.put("newProductViewCount", newProductViewCount);
            //收藏产品数
            Long collectProductCount = merchantProductRepository.getProductFavoriteCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (collectProductCount == null) {
                collectProductCount = 0l;
            }
            resultMap.put("collectProductCount", collectProductCount);
            //加购产品数
            Long lastBuyProductCount = merchantProductRepository.getLatestBuyProductCountStatisticsYesterDay(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (lastBuyProductCount == null) {
                lastBuyProductCount = 0l;
            }
            resultMap.put("lastBuyProductCount", lastBuyProductCount);
            //热销产品列表（头３个产品）
            List top3ProductSelling = merchantProductRepository.getTop3SellingList(userInfoDto.mall.getId(), userInfoDto.merchant.getId());

            resultMap.put("top3ProductSelling", top3ProductSelling);
            //新客户数
            Long newCustomerCount = merchantRepository.getNewCustomerCount(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (newCustomerCount == null) {
                newCustomerCount = 0l;
            }
            resultMap.put("newCustomerCount", newCustomerCount);
            // 新客户下单数
            Long newCustomerOrderCount = merchantRepository.getNewCustomerOrderCount(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (newCustomerOrderCount == null) {
                newCustomerOrderCount = 0l;
            }
            resultMap.put("newCustomerOrderCount", newCustomerOrderCount);
            //新客户购买金额
            Double newCustomerOrderTotal = merchantRepository.getNewCustomerOrderTotal(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (newCustomerOrderTotal == null) {
                newCustomerOrderTotal = 0d;
            }
            resultMap.put("newCustomerOrderTotal", BigDecimalUtils.setScale(newCustomerOrderTotal));
            //新客户－客单价（平均购买金额）
            Double newCustomerOrderAvg = 0d;
            if (newCustomerCount != 0 && newCustomerOrderTotal != 0) {
                newCustomerOrderAvg = newCustomerOrderTotal / newCustomerCount;
            }

            if (newCustomerOrderAvg == null) {
                newCustomerOrderAvg = 0d;
            }
            resultMap.put("newCustomerOrderAvg", BigDecimalUtils.setScale(newCustomerOrderAvg));
            //老客户数
            Long oldCustomerCount = merchantRepository.getOldCustomerCount(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (oldCustomerCount == null) {
                oldCustomerCount = 0l;
            }
            resultMap.put("oldCustomerCount", oldCustomerCount);
            //老客户下单数
            Long oldCustomerOrderCount = merchantRepository.getOldCustomerOrderCount(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (oldCustomerOrderCount == null) {
                oldCustomerOrderCount = 0l;
            }
            resultMap.put("oldCustomerOrderCount", oldCustomerOrderCount);
            //老客户购买金额
            Double oldCustomerOrderTotal = merchantRepository.getOldCustomerOrderTotal(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (oldCustomerOrderTotal == null) {
                oldCustomerOrderTotal = 0d;
            }
            resultMap.put("oldCustomerOrderTotal", BigDecimalUtils.setScale(oldCustomerOrderTotal));
            //老客户－客单价（平均购买金额）
            Double oldCustomerOrderAvg = 0d;
            if (oldCustomerCount != 0 && oldCustomerOrderTotal != 0) {
                oldCustomerOrderAvg = oldCustomerOrderTotal / oldCustomerCount;

            }
            resultMap.put("oldCustomerOrderAvg", BigDecimalUtils.setScale(oldCustomerOrderAvg));
            //优惠券数量
            Long couponCount = merchantCouponRepository.getCouponCount(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (couponCount == null) {
                couponCount = 0l;
            }
            resultMap.put("couponCount", couponCount);
            //礼包数量
            Long giftPacketCount = merchantGiftPacketRepository.getGiftPacketCount(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if (giftPacketCount == null) {
                giftPacketCount = 0l;
            }
            resultMap.put("giftPacketCount", giftPacketCount);
            //渠道活跃指数　根据渠道访问量，出售量，下单转化率　从高到低排列
//            List<ChannelDto> top5Channels = merchantChannelRepository.getTop5Channel(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            List<ChannelDto> top5Channels = new ArrayList<>();
            ChannelDto channelDto = new ChannelDto();
            channelDto.setPageSize(20);
            PageResult<ChannelDto> channels = merchantChannelStatisticsService.findTop5ActiveChannels(getPage(channelDto.getPageNo(),channelDto.getPageSize()),userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            if(channels!=null) {
                top5Channels.addAll(channels.data);
            }
            resultMap.put("top5Channels", top5Channels);
            //帮助中心文章列表
            List<ArticleDto> top5Article = articleRepository.getTop5Article(userInfoDto.mall.getId());
            resultMap.put("top5Article", top5Article);
            jsonResult.data = resultMap;
        };

        return doing.go(request, log);
    }


    /**
     *
     * @api {put} /merchant/send/out B端 商户管理 推广
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiSuccessExample {json} Success-Response:
     *{
     *"code": "1",
     *"desc": "成功",
     *"data": {
     *   "promoteUrl": "http://uploads.rockcent.com/dev/coupon/promote/201611/8144438785f0d66d37-682d-424f-a9c2-5bf3c270d4c7giftPacketPromote.jpg",
     *   "sendOutUrl": "http://beta.c.dev.rockcent.com/mall.php?method=detail&couponId=133&salesCode=B@AfvahtT"
     *  }
     *}
     **/
    @RequestMapping(value = Routes.MERCHANT_SEND_OUT, method = RequestMethod.PUT)
    public JsonResult sendOutMerchant(HttpServletRequest request) {

        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if (mall == null) {
                jsonResult.remind("平台不存在,请联系开发人员",log);
                return;
            }
            Merchant merchant = merchantRepository.findOne(userInfoDto.merchant.getId());
            String host = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(host)) {
                host = mall.getMobileHostName();
            }
            StringBuffer url = new StringBuffer();
            //推广链接，待定
            url.append("http://").append(host).append("/wechat/merchant/" + merchant.getId()).append("/?id=").append(merchant.getId());


            QrCodeDto qrCodeDto = new QrCodeDto();
            qrCodeDto.setId(userInfoDto.getId());
            qrCodeDto.setMallId(userInfoDto.mall.getId());
            qrCodeDto.setMerchantId(userInfoDto.merchant.getId());
            UploadImageFileDto uploadImageFileDto = qrCodeHelper.createQRCode(qrCodeDto, url.toString(), "merchantSendOutQR.jpg", UploadFileBusinessType.MERCHANT_PROMOTE, prop.env, prop.aliyunOssBucketName, prop.domainUploadsHttp);
            merchant.setPromoteUrl(uploadImageFileDto.getPath());
            merchantRepository.save(merchant);
            MerchantDto merchantDto = new MerchantDto();
            merchantDto.setSendOutUrl(url.toString());
            merchantDto.setPromoteUrl(merchant.getPromoteUrl());
            jsonResult.data = merchantDto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /merchant/bank/save B端 商户管理 银行卡绑定
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     *
     * @apiParam {String} companyName <code>必传参数</code> 企业名称
     * @apiParam {String} bankNo <code>必传参数</code> 银行卡号
     * @apiParam {String} bankCode <code>必传参数</code> 银行编码 选择 其他 时,传OTHER
     * @apiParam {String} bankName <code>必传参数</code> 开户银行
     * @apiParam {String} bankBranchName <code>必传参数</code> 开户银行支行银行名称
     *
     * @apiSuccessExample {json} Success-Response:
     *{
     *  "code": "1",
     *  "desc": "成功",
     *}
     **/
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_BANK_SAVE, method = RequestMethod.POST)
    public JsonResult merchantBankSave(HttpServletRequest request, @RequestBody MerchantBankDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            String companyName = dto.getCompanyName();
            if (StringUtils.isBlank(companyName)) {
                jsonResult.remind("开户名 不能为空",log);
                return;
            }

            String dtoBankNo = dto.getBankNo();
            if (StringUtils.isBlank(dtoBankNo)) {
                jsonResult.remind("银行卡号 不能为空",log);
                return;
            }

            String dtoBankCode = dto.getBankCode();
            if (StringUtils.isBlank(dtoBankCode)) {
                jsonResult.remind("银行编码  不能为空",log);
                return;
            }

            String dtoBankName = dto.getBankName();
            if (StringUtils.isBlank(dtoBankName)) {
                jsonResult.remind("银行名称 不能为空",log);
                return;
            }

            String dtoBankBranchName = dto.getBankBranchName();
            if (StringUtils.isBlank(dtoBankBranchName)) {
                jsonResult.remind("银行支行名称 不能为空",log);
                return;
            }

            Long anUserInfoDtomallId = userInfoDto.mall.getId();
            Long anUserInfoDtomerchantId = userInfoDto.merchant.getId();
            MerchantCertify merchantCertify = merchantCertifyRepository.findByMerchantIdAndMallId(anUserInfoDtomerchantId, anUserInfoDtomallId);
            if (merchantCertify == null) {
                jsonResult.remind("商家还没有进行企业认证",log);
                return;
            }
            CertifyType merchantCertifyType = merchantCertify.getType();
            if (merchantCertifyType == CertifyType.PERSONAL) {
                String merchantCertifyRealName = merchantCertify.getRealName();
                if (null != merchantCertifyRealName && !companyName.equals(merchantCertifyRealName)) {
                    jsonResult.remind("真实姓名与商家认证的真实姓名不符合",log);
                    return;
                }
            }
            else if (merchantCertifyType == CertifyType.COMPANY) {
                String merchantCertifyCompanyName = merchantCertify.getCompanyName();
                if (null != merchantCertifyCompanyName && !companyName.equals(merchantCertifyCompanyName)) {
                    jsonResult.remind("企业名称与商家认证的企业名称不符合",log);
                    return;
                }
            }

//            MerchantBank merchantBank = merchantBankRepository.findByBankNoAndIsDelete(dtoBankNo, Whether.NO);
//            if (null != merchantBank) {
//                jsonResult.remind("此银行卡号已经被绑定");
//                return;
//            }

            MerchantBank merchantBank  = merchantBankRepository.findByMerchantIdAndMallIdAndIsDelete(anUserInfoDtomerchantId, anUserInfoDtomallId, Whether.NO);
            if (null != merchantBank) {
                merchantBank.setIsDelete(Whether.YES);
                merchantBankRepository.save(merchantBank);
//                jsonResult.remind("只能绑定一张银行卡");
//                return;
            }
            merchantBank = new MerchantBank();
//            if (merchantBank == null) {
//
//            }
            merchantBank.setMallId(anUserInfoDtomallId);
            merchantBank.setMerchantId(anUserInfoDtomerchantId);
            merchantBank.setBankCode(dtoBankCode);
            merchantBank.setBankName(dtoBankName);
            merchantBank.setBankNo(dtoBankNo);
            merchantBank.setBankAccountName(companyName);
            merchantBank.setIsDelete(Whether.NO);
            merchantBank.setBankBranchName(dtoBankBranchName);
            merchantBankRepository.save(merchantBank);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/bank/info B端 商户管理 商家银行卡信息
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     *
     * @apiSuccess {String} bankName 银行名称
     * @apiSuccess {String} bankNo 帐号
     * @apiSuccess {String} bankCode 银行编码
     * @apiSuccess {String} bankAccountName 开户名
     * @apiSuccess {String} bankBranchName 开户银行支行银行名称
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *      "bankName" : "招商",
     *      "bankNo" : "2134772834657234",
     *      "bankCode" : "ICBC",
     *      "bankAccountName" : "张三"
     *      }
     *  }
     **/
    @RequestMapping(value = Routes.MERCHANT_BANK_INFO, method = RequestMethod.GET)
    public JsonResult merchantBankInfo(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            MerchantBank merchantBank = merchantBankRepository.findByMerchantIdAndMallIdAndIsDelete(userInfoDto.merchant.getId(), userInfoDto.mall.getId(), Whether.NO);
            if (merchantBank != null) {
                MerchantCertify merchantCertify = merchantCertifyRepository.findByMerchantIdAndMallId(userInfoDto.merchant.getId(), userInfoDto.mall.getId());
                if (merchantCertify != null) {
                    if (merchantCertify.getCompanyName() != null && CertifyType.COMPANY == merchantCertify.getType()) {
                        merchantBank.setBankAccountName(merchantCertify.getCompanyName());
                    }
                    if (merchantCertify.getRealName() != null && CertifyType.PERSONAL == merchantCertify.getType()) {
                        merchantBank.setBankAccountName(merchantCertify.getRealName());
                    }
                }
            }

            jsonResult.data = merchantBank;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /merchant/bank/delete B端 商户管理 商家银行卡删除
     * @apiGroup merchant
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     *
     * @apiParam {String} bankNo <code>必传参数</code> 银行卡号
     * @apiParam {String} bankAccountName <code>必传参数</code> 银行开户名
     *
     * @apiSuccessExample {json} Success-Response:
     *  {
     *  "code": "1",
     *  "desc": "成功"
     **/
    @RequestMapping(value = Routes.MERCHANT_BANK_DELETE, method = RequestMethod.PUT)
    public JsonResult merchantBankDelete(HttpServletRequest request, @RequestBody MerchantBankDto dto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getBankNo())) {
                jsonResult.remind("银行卡号 不能为空",log);
                return;
            }

            if (StringUtils.isBlank(dto.getBankAccountName())) {
                jsonResult.remind("开户名  不能为空",log);
                return;
            }

            MerchantBank merchantBank = merchantBankRepository.findByMerchantIdAndBankNoAndMallIdAndBankAccountNameAndIsDelete(userInfoDto.merchant.getId(), dto.getBankNo(), userInfoDto.mall.getId(), dto.getBankAccountName(), Whether.NO);
            if (merchantBank == null) {
                jsonResult.remind("银行帐号不存在",log);
                return;
            }
            merchantBank.setIsDelete(Whether.YES);
            merchantBankRepository.save(merchantBank);
        };
        return doing.go(request, log);
    }

}
